module.exports = class extends think.Model {
  /**
   * 创建评论
   */
  async create({
    userId,
    informationId,
    toUserId = 0,
    content
  }) {
    try {
      await this.startTrans();
      const data = think.snakeObject({
        userId,
        informationId,
        toUserId,
        content
      });
      data.create_time = think.datetime();
      const newId = await this.add(data);
      await this.model('information').db(this.db()).where({id: informationId}).increment('comment_count', 1);
      await this.commit();
      return newId;
    } catch (e) {
      think.logger.error('create comments:error:', e.message);
      await this.rollback();
      throw e;
    }
  }
  // 删除指定用户的评论
  async removeUserCommentById(id, userId) {
    const where = {
      id,
      user_id: userId
    };
    try {
      await this.startTrans();
      const informationId = await this.where(where).getField('information_id', true) || 0;
      await this.where(where).delete();
      await this.model('information').db(this.db()).where({id: informationId}).decrement('comment_count', 1);
      await this.commit();
    } catch (e) {
      think.logger.error('remove comments:error:', e.message);
      await this.rollback();
      throw e;
    }
  }
  // 查找用户发布的评论
  queryDataListByUserId(userId, {
    page,
    pageSize,
    order = 'id desc'
  }) {
    return this.where({
      user_id: userId
    }).page(page, pageSize).order(order).field(['content',
      'information_id', 'to_user_id', 'create_time',
      '(select content from information where id=comments.information_id) information_content'
    ]).select();
  }
  // 查找用户被评论信息
  queryCommentedDataByUserId(userId, field = '*') {
    return this.where({
      to_user_id: userId
    }).field(field).select();
  }

  // 查找某information下的评论
  async queryCommentsOfInformation(informationId, {
    page = 1,
    order = 'id desc',
    lastId = 0,
    pageSize = 10
  }) {
    const where = {
      information_id: informationId
    };
    if (lastId > 0) {
      where.id = ['lt', lastId];
    }
    const rows = await this.where(where)
      .field(['content', 'user_id', 'create_time', 'to_user_id', 'id'])
      .limit(pageSize).order(order).select();
    return rows;
  }
  queryNextCommentOfOneId(commentId, informationId) {
    return this.where({id: ['lt', commentId], information_id: informationId}).order('id desc').find();
  }
  // 查找information下的留言列表
  queryByInformationIdRange(idArr) {
    if (think.isEmpty(idArr)) {
      return [];
    }
    const where = {
      information_id: ['in', idArr]
    };
    return this.where(where)
      .field(['content', 'user_id', 'create_time', 'to_user_id', 'id', 'information_id'])
      .order('id asc')
      .select();
  }
};
